﻿using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.UI;

public class RankingController : MonoBehaviour
{
    public static GameObject ItemPFB;
    public static GameObject Root;
    public static Text ErrorText;

    private static List<Ranking> _newRankings;
    private static List<Ranking> _rankings;
    public static List<Ranking> Rankings
    {
        set
        {
            if (value.Count == 0) return;
            RectTransform transform = Root.GetComponent<RectTransform>();
            int childCount = transform.childCount;
            for (int i = 0; i < childCount; i++)
                Destroy(transform.GetChild(0).gameObject);
            foreach (Ranking ranking in value)
            {
                GameObject o = Instantiate(ItemPFB, transform);
                o.name = value.IndexOf(ranking).ToString();
                o.GetComponent<RankingItemView>().Ranking = ranking;
            }
            transform.sizeDelta = new Vector2(800, value.Count * 110);
            transform.position = new Vector2(0, -value.Count * 110);
            _rankings = value;
        }
    }

    private void Start()
    {
        ItemPFB = Resources.Load<GameObject>("RankingItem");
        Root = GameObject.Find("RankPost");
        ErrorText = GameObject.Find("Text_ConnectError").GetComponent<Text>();
        UpdateRanking();
    }

    private void Update()
    {
        if (_rankings != _newRankings) { Rankings = _newRankings; }
    }

    public static void UpdateRanking()
    {
        TCPClient.Request = new Request(
            ConfigManager.LoadSettings().Username,
            Request.GET_RANKING_REQUEST,
            RoundxController.SelectRoundIndex
        );
        TCPClient.SendRequest();
    }

    public static void DownloadRankingCallBack(string json)
    {
        if (TCPClient.ClientSocket.Connected)
        {
            if (TCPClient.Error == System.Net.Sockets.SocketError.Success)
            {
                _newRankings = JsonConvert.DeserializeObject<List<Ranking>>(json);
                ErrorText.text = string.Empty;
            }
            else
            {
                ErrorText.text = "什么情况？";
                Debug.Log(TCPClient.Error);
            }
        }
        else { ErrorText.text = "连接服务器失败"; }
    }
}
